package com.wkhyapp.lm.view;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.wkhyapp.lm.R;
import com.wkhyapp.lm.adapter.FansAdapter;
import com.wkhyapp.lm.adapter.SelectImageApdater;
import com.wkhyapp.lm.base.SuperActivity;
import com.wkhyapp.lm.constant.Constant;
import com.wkhyapp.lm.contract.UpLoadPresenter;
import com.wkhyapp.lm.contract.UploadView;
import com.wkhyapp.lm.http.net.AddGoodsRequest;
import com.wkhyapp.lm.http.net.GoodsReq;
import com.wkhyapp.lm.http.vo.Category;
import com.wkhyapp.lm.http.vo.Fans;
import com.wkhyapp.lm.http.vo.Goods;
import com.wkhyapp.lm.utils.GlideLoader;
import com.wkhyapp.lm.utils.IdUtils;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.utils.StatusBarFontUtil;
import com.wkhyapp.lm.weigit.dialog.CategoryDialog;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class EditorGoodsActivity extends SuperActivity<UpLoadPresenter> implements UploadView {

    private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();
    private Goods goods;
    @BindView(R.id.back_iv)
    ImageView back_iv;
    @BindView(R.id.et_context)
    EditText et_context;
    @BindView(R.id.fl_tv)
    TextView fl_tv;
    @BindView(R.id.price_et)
    EditText price_et;
    int fenlei = 0;
    @BindView(R.id.gridView_gv)
    GridView gridView;
    CategoryDialog categoryDialog;
    @BindView(R.id.category_rl)
    RelativeLayout category_rl;
    private List<Category> categories = new ArrayList<>();
    @BindView(R.id.find_comment_submit)
    TextView tv_click;
    SelectImageApdater selectImageApdater;
    private ArrayList<String> upLoadImg = new ArrayList<>();
    @Override
    public void initUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            translucentStatusBar();
        }
        StatusBarFontUtil.setLightStatusBarColor(this);
        goods = (Goods) getIntent().getSerializableExtra("0");
        et_context.setText(goods.getDesc());
        fl_tv.setText(goods.getCategoryId()+"");
        if(goods.getCategoryId()!=null){
            fl_tv.setText(goods.getCategoryId()+"");
        }else{
            fl_tv.setText("全部");
            fenlei  = 0;
        }

        if(goods.getPrice()!=null){
            price_et.setText(goods.getPrice().toString());
        }else{
            price_et.setText("0.00");
        }


        imagePaths.addAll(goods.getGoodsImgs());
        imgList.addAll(goods.getGoodsImgs());
        if(imgList.size()<9){
            imgList.add("add");
        }

        mPresenter.getCategry(MemberUtils.getUid());
        selectImageApdater = new SelectImageApdater(mContext,imgList,R.layout.item_xc);
        gridView.setAdapter(selectImageApdater);
        selectImageApdater.notifyDataSetChanged();
        mPresenter.getCategry(MemberUtils.getUid());
    }

    @Override
    protected void initListener() {
        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        selectImageApdater.setCallBack(new SelectImageApdater.callBack() {
            @Override
            public void add(String item) {
                if("add".equals(item)){
                    ImageConfig imageConfig
                            = new ImageConfig.Builder(EditorGoodsActivity.this , new GlideLoader())
                            // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                            .steepToolBarColor(getResources().getColor(R.color.black))
                            // 标题的背景颜色 （默认黑色）
                            .titleBgColor(getResources().getColor(R.color.black))
                            // 提交按钮字体的颜色 （默认白色）
                            .titleSubmitTextColor(getResources().getColor(R.color.white))
                            // 标题颜色 （默认白色）
                            .titleTextColor(getResources().getColor(R.color.white))
                            // 开启多选 （默认为多选） (单选 为 singleSelect)
                            .mutiSelect()
                            // 多选时的最大数量 （默认 9 张）
                            .mutiSelectMaxSize(9)
                            // 已选择的图片路径
                            .pathList(imagePaths)
                            // 拍照后存放的图片路径（默认 /temp/picture）
                            .filePath("/ImageSelector/Pictures")
                            // 开启拍照功能 （默认关闭）
                            .build();
                    ImageSelector.open(imageConfig); // 开启图片选择器
                }
            }

            @Override
            public void delete(String item) {
                imagePaths.remove(item);
                imgList.remove(item);
                if(imgList.size()<9){
                    if(!isExt("add")){
                        imgList.add("add");
                    }
                }
                selectImageApdater.notifyDataSetChanged();
            }
        });
        category_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                categoryDialog.show();
            }
        });

        tv_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(et_context.getText().toString())){
                    TToast("请输入商品介绍");
                    return;
                }
                if("".equals(price_et.getText().toString())){
                    price_et.setText("0.00");
                }

                if(imgList.size()<=1){
                    TToast("上传商品图片");
                    return;
                }
                showLoad("正在修改...");
                imgList.remove("add");
                mPresenter.getToken();
            }
        });
    }





    @Override
    public void setToken(String toekn) {
        for(String s:imgList){

            if(!s.startsWith("http")){
                uploadImg2QiNiu(s, MemberUtils.getUid()+"",toekn);
                //imgList.remove(s);
            }
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imgList.addAll(upLoadImg);
                for(int i=0;i<imgList.size();i++){
                    if(!imgList.get(i).startsWith("http")){
                        imgList.remove(i);
                    }
                }
                GoodsReq request = new GoodsReq();
                request.setId(goods.getId());
                request.setDesc(et_context.getText().toString());
                request.setCategoryId(fenlei);
                request.setPrice(price_et.getText().toString());
                request.setUserId(MemberUtils.getUid());
                request.setGoodsImgs(imgList);
                mPresenter.updateGoods(request);
            }
        },2000);
    }


    Configuration config = new Configuration.Builder().build();
    UploadManager uploadManager = new UploadManager(config);
    private void uploadImg2QiNiu(String data,String userId,String token) {
        String key = userId+"_"+System.currentTimeMillis()+"_"+ IdUtils.getShartUUID()+".jpg";
        Log.i("token", token);
        upLoadImg.add(Constant.qiniuUrl+key);
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if(info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                        } else {
                            Log.i("qiniu", "Upload Fail");
                        }
                    }
                }, null);
    }



    @Override
    public void upLoadSucc() {
        TToast("修改成功");
        dismissLoad();
        finish();
    }

    @Override
    public void setCategoory(List<Category> list) {
        Category category = new Category();
        category.setName("全部");
        category.setId(0);
        list.add(0,category);
        categories.addAll(list);
        categoryDialog = new CategoryDialog(mContext,categories);
        categoryDialog.init();
        categoryDialog.setCallBack(new CategoryDialog.callBack() {
            @Override
            public void jump(Category item) {
                fenlei = item.getId();
                fl_tv.setText(item.getName());
            }
        });
    }

    @Override
    protected UpLoadPresenter createPresenter() {
        return mPresenter = new UpLoadPresenter(this);
    }


    @Override
    protected void afterCreate() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_editor_goods;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            // Get Image Path List
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            imgList.clear();
            if(pathList.size()<9){
                imgList.addAll(pathList);
                if(!isExt("add")){
                    imgList.add("add");
                }
            }else{
                imgList.addAll(pathList);
            }
            selectImageApdater.notifyDataSetChanged();
            for (String path : imgList) {
                Log.e("已选择图片的路径为-----", path);
            }
        }
    }


    public boolean isExt(String item){
        boolean isExt = false;
        for(String s:imgList){
            if(s.equals(item)){
                isExt = true;
                break;
            }else{
                isExt =false;
            }
        }
        return isExt;
    }


}
